package com.ywu.boot.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.result.CommonResult;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @ClassName YwuMvcBlockExceptionHandler
 * @Description TODO
 * @Author GroundDemo
 * @Date 2025/4/16 9:39
 * @Version 1.0
 **/
@Component
public class YwuMvcBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
        response.setStatus(400);
        PrintWriter out = response.getWriter();
        CommonResult<Object> result = CommonResult.error().setErrorCode("block.by.sentinel").setMessage("Blocked by Sentinel (flow limiting)");
        out.print(GsonUtils.serialize(result));
        out.flush();
        out.close();
    }
}
